import torch
import torch.nn as nn
import numpy
from ai.data_center import Data_Center
from database.dbop import Database
import database.sql as Sql
import src.global_config as gl
import json
from src.go import Go


# 终于写到围棋ai的核心模块啦
class Honinbo:
    board = []
    color = 'black'
    go = None
    data_center = None
    models = None

    def __init__(self):
        print("torch.cuda.is_available()", torch.cuda.is_available())
        self.go = Go()
        self.data_center = Data_Center()

    # 对接收到的信息做处理
    def parse_operator(self, data):
        # 收到的数据转json
        print("honinbo收到的原生数据为", data)
        data_dict = json.loads(data)
        print(data_dict)
        # 转换成引擎识别的数据
        # 引擎分析
        if data_dict['operator'] == 'run':
            self.parse_step_data(data_dict)
            # 棋盘数据转张量，参数int或float 不传默认int
            board_tensor = self.parse_board_to_tensor('float')
            print(board_tensor)
        # 保存棋谱
        elif data_dict['operator'] == 'saveGoban':
            goban = data_dict['goban']
            print("收到的棋谱为", goban)
            if len(goban) == 0:
                return {
                    "code": -1,
                    "message": "空棋谱不进行处理"
                }
            # 棋谱是单独的json 再解析一次
            goban = json.loads(goban)
            parsed = self.go.parse_goban_to_sgf(goban)
            additional = self.go.parse_additional_sgf(goban)
            res = self.data_center.save_goban(parsed, additional)
            return res

    # 棋盘数据转张量
    def parse_board_to_tensor(self, option):

        if option == 'float':
            return torch.tensor(self.board, dtype=torch.float)
        else:
            return torch.tensor(self.board, dtype=torch.int)

    # 获取引擎需要的数据
    def parse_step_data(self, raw_data):
        self.board = raw_data['board']
        self.color = raw_data['color']

    def set_models(self, dicts):
        self.models = dicts

